<?php
	require_once("../functions.php");
	if(!isLoggedIn()){
		header("location:index.php?message=".urlencode("Please login first."));
		die();
	}
	
	$con = connectToDB();
	
	if(!isset($_POST["username"])){
		echo "An error occurred.";
		die();
	}
	
	$uname = mysql_real_escape_string($_POST["username"]);
	$first = mysql_real_escape_string($_POST["first"]);
	$last = mysql_real_escape_string($_POST["last"]);
	$bdate = $_POST["birthdate"];
	$occ = (isset($_POST["occupation"])) ? mysql_real_escape_string($_POST["occupation"]) : NULL;
	$org = (isset($_POST["organization"])) ? mysql_real_escape_string($_POST["organization"]) : NULL;
	
	if(isset($_POST["old"])){
		$oldpword = mysql_real_escape_string($_POST["old"]);
		$newpword = mysql_real_escape_string($_POST["password"]);
		$sql = "update user set username='$uname',password='$newpword',first='$first',last='$last',birthdate='$bdate',occupation='$occ',organization='$org' where username='$_SESSION[username]' and password='$oldpword'";
	}else{
		$sql = "update user set username='$uname',first='$first',last='$last',birthdate='$bdate',occupation='$occ',organization='$org' where username='$_SESSION[username]'";
	}
	
	$result = mysql_query($sql, $con);
	if (!$result) {
		echo mysql_error() . "<br />" . $sql;
		die();
	}
	
	$nrows = mysql_affected_rows($con);
	$info = get_mysql_info();
	
	if($info["rows_matched"]==1 || $nrows==1){
		echo '<br /><p class="center" style="color:green;font-weight:bold">You have successfully updated your account.</p>';
	}else if($nrows>1){
		echo '<br /><p class="center" style="color:red;font-weight:bold">Other user accounts corrupted.</p>';
	}else{
		echo '<br /><p class="center" style="color:red;font-weight:bold">Updated unsuccessful. Please recheck your old password.</p>';
	}
	
	$_SESSION['username'] = $uname;
	
	if(isset($_POST["old"])){
		$_SESSION['password'] = mysql_real_escape_string($_POST["password"]);
	}
?>